<template>
  <div class="app-container">
    <!--个人信息显示-->
    <el-row :gutter="20">
      <el-col :span="3">用户名</el-col>
      <el-col :span="6">{{ temp.username }}</el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="3">真实姓名</el-col>
      <el-col :span="6">
        <el-input v-model="temp.realName" type="text" placeholder="真实姓名" size="medium" clearable style="width: 200px;" @blur="handleEditName" />
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="3">手机号</el-col>
      <el-col :span="5">{{ temp.phone || '未绑定' }}</el-col>
      <el-col :span="2">
        <el-button v-if="temp.phone" type="text" @click="handleBand('phone')">修改</el-button>
        <el-button v-else type="text" @click="handleBand('phone')">绑定</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="3">邮箱</el-col>
      <el-col :span="5">{{ temp.email || '未绑定' }}</el-col>
      <el-col :span="2">
        <el-button v-if="temp.email" type="text" @click="handleBand('email')">修改</el-button>
        <el-button v-else type="text" @click="handleBand('email')">绑定</el-button>
      </el-col>
    </el-row>
    <!--<el-row :gutter="20">-->
    <!--  <el-col :span="3">微信</el-col>-->
    <!--  <el-col :span="5">{{ temp.openId? '已绑定' : '未绑定' }}</el-col>-->
    <!--  <el-col :span="2">-->
    <!--    <el-button v-if="temp.openId" type="text" @click="handleBand('weChat')">换绑</el-button>-->
    <!--    <el-button v-else type="text" @click="handleBand('weChat')">绑定</el-button>-->
    <!--  </el-col>-->
    <!--</el-row>-->
    <el-row :gutter="20">
      <el-col :span="3">上次登录时间</el-col>
      <el-col :span="5">{{ temp.lastLoginTime }}</el-col>
    </el-row>

    <!--绑定邮箱对话框-->
    <el-dialog title="绑定邮箱" :visible.sync="dialogEmailVisible" width="400px" @close="dialogClose">
      <!--邮箱-->
      <el-form
        ref="emailRef"
        :model="dialogData"
        :rules="emailRule"
        label-position="left"
        label-width="80px"
        hide-required-asterisk
      >
        <el-form-item label="邮箱地址" prop="number">
          <el-input v-model="dialogData.number" type="text" placeholder="邮箱地址" clearable />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="dialogData.code" type="text" placeholder="验证码">
            <el-button slot="append" :disabled="isDisabled" @click="handleValid">{{ codeBtnText === '获取验证码' ? codeBtnText : codeBtnText + 's' }}</el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogEmailVisible = false">取消</el-button>
          <el-button type="primary" @click="bandEmail">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--绑定手机号对话框-->
    <el-dialog title="绑定手机" :visible.sync="dialogPhoneVisible" width="400px" @close="dialogClose">
      <el-form
        ref="phoneRef"
        label-position="left"
        label-width="80px"
        hide-required-asterisk
        :rules="phoneRule"
        :model="dialogData"
      >
        <el-form-item label="手机号" prop="number">
          <el-input v-model="dialogData.number" type="text" placeholder="手机号" clearable />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="dialogData.code" type="text" placeholder="验证码">
            <el-button slot="append" :disabled="isDisabled" @click="handleValid">{{ codeBtnText === '获取验证码' ? codeBtnText : codeBtnText + 's' }}</el-button>
          </el-input>
        </el-form-item>
      </el-form>
      <el-row style="margin: 0;">
        <el-col :span="14" />
        <el-button @click="dialogPhoneVisible = false">取消</el-button>
        <el-button type="primary" @click="bandPhone">确认</el-button>
      </el-row>
    </el-dialog>

    <!--图形验证码对话框-->
    <el-dialog title="行为验证" :visible.sync="dialogVerifyVisible" width="370px">
      <verify
        :captcha-type="'blockPuzzle'"
        :mode="'fixed'"
        :img-size="{ width: '330px', height: '155px' }"
        @success="sendValidCode"
      />
    </el-dialog>
  </div>
</template>

<script>
import Verify from '@/components/verifition/Verify'
import { getInfo, updateUserByToken } from '@/api/user'
import { parseTime } from '@/utils'
import { bandEmail, bandPhone, sendEmailCode, sendPhoneCode } from '@/api/verity'

export default {
  name: 'PersonInfo',
  components: { Verify },
  data() {
    // 验证手机号码的规则
    const checkMobile = (rule, value, cb) => {
      // 验证手机号码的正则表达式
      const regMobile = /^1(3[0-9]|4[5,7]|5[012356789]|6[2567]|7[0,178]|8[0-9]|9[189])\d{8}$/
      if (regMobile.test(value) || value === '') {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }

    return {
      // 用户信息
      temp: {
        username: '',
        email: '',
        phone: '',
        lastLoginTime: '',
        realName: '',
        openId: ''
      },
      // 姓名校验
      validName: '',
      // 对话框类型
      dialogStatus: 'email',
      // 对话框可见性
      dialogVisible: false,
      // 绑定邮箱对话框可见性
      dialogEmailVisible: false,
      // 绑定手机对话框可见性
      dialogPhoneVisible: false,
      // 对话框文本
      textMap: {
        phone: '手机绑定',
        email: '邮箱绑定',
        weChat: '微信绑定'
      },
      // 手机号、邮箱
      dialogData: {
        number: '',
        code: ''
      },
      // 验证码对话框
      dialogVerifyVisible: false,
      // 验证码禁用
      isDisabled: false,
      // 获取验证码按钮
      codeBtnText: '获取验证码',
      // 绑定成功标志
      isBanded: false,
      // 邮箱校验规则
      emailRule: {
        number: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      // 邮箱校验规则
      phoneRule: {
        number: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUser()
  },
  methods: {
    // 获取用户信息
    getUser() {
      getInfo().then(res => {
        this.temp = res.data
        this.temp.lastLoginTime = parseTime(this.temp.lastLoginTime, '{y}年{m}月{d}日 {h}:{i}:{s}')
        this.validName = res.data.realName
      })
    },
    // 处理修改用户名
    handleEditName() {
      if (this.temp.realName.trim() !== '' && this.temp.realName.trim() !== this.validName) {
        this.validName = this.temp.realName.trim()
        const data = {
          realName: this.temp.realName
        }
        updateUserByToken(data).then(res => {
          this.$notify({
            title: '成功',
            message: res.msg,
            type: 'success',
            duration: 2000
          })

          // 更新用户名后修改用户信息，存入缓存
          this.$store.commit('user/SET_REAL_NAME', this.temp.realName)
        }).catch(() => {
          this.temp.realName = this.validName
        })
      }
    },
    // 绑定处理
    handleBand(status) {
      this.dialogStatus = status
      if (status === 'email') {
        this.dialogEmailVisible = true
      } else if (status === 'phone') {
        this.dialogPhoneVisible = true
      }
    },
    // 处理获取验证码验证, 打开验证码对话框
    handleValid() {
      if (this.dialogStatus === 'email') {
        this.$refs.emailRef.validate((valid) => {
          if (valid) {
            this.dialogVerifyVisible = true
          }
        })
      } else {
        this.$refs.phoneRef.validate((valid) => {
          if (valid) {
            this.dialogVerifyVisible = true
          }
        })
      }
    },
    // 验证成功，发送验证码，换绑
    sendValidCode() {
      this.isDisabled = true
      this.dialogVerifyVisible = false
      // 调用计时器
      this.countdown()
      // 发送邮箱验证码
      if (this.dialogStatus === 'email') {
        this.sendEmailCode()
      } else {
        // 发送手机验证码
        this.sendPhoneCode()
      }
    },
    // 验证码计时器
    countdown() {
      this.codeBtnText = 120
      const _this = this
      const second = setInterval(function() {
        _this.codeBtnText--
        if (_this.isBanded || _this.codeBtnText === 0) {
          clearInterval(second)
          _this.codeBtnText = '获取验证码'
          _this.isDisabled = false
          _this.isBanded = false
        }
      }, 1000)
    },
    // 发用邮箱验证码
    sendEmailCode() {
      sendEmailCode(this.dialogData.number).then(res => {
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success',
          duration: 2000
        })
      })
    },
    // 发送手机验证码
    sendPhoneCode() {
      sendPhoneCode(this.dialogData.number).then(res => {
        this.$message.success('验证码：' + res.data)
      })
    },
    // 绑定对话框关闭事件
    dialogClose() {
      this.isBanded = true
      this.resetData()
      if (this.dialogStatus === 'phone') {
        this.$refs.phoneRef.resetFields()
      } else if (this.dialogStatus === 'email') {
        this.$refs.emailRef.resetFields()
      }
    },
    // 绑定邮箱
    bandEmail() {
      bandEmail(this.dialogData).then(res => {
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success',
          duration: 2000
        })
        this.dialogEmailVisible = false
        this.getUser()
      })
    },
    // 绑定手机
    bandPhone() {
      const data = {
        phone: this.dialogData.number,
        code: this.dialogData.code
      }
      bandPhone(data).then(res => {
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success',
          duration: 2000
        })
        this.dialogPhoneVisible = false
        this.getUser()
      })
    },
    // 重置表单
    resetData() {
      this.dialogData = {
        number: '',
        code: ''
      }
    }
  }
}
</script>

<style scoped>
/*noinspection CssUnusedSymbol*/
.el-row {
  margin: 15px 0;
  display: flex;
  align-items: center;
}
</style>
